import json
import re

from django.http import JsonResponse
from django.views import View

from ihome.utils.fastdfs.fastdfs_storage import FastDFSStorage
from ihome.utils.views import LoginRequiredMixin
from wangziye.models import Area, User, House


class AreasList(View):
    '''地区列表展示'''

    def get(self, request):
        # 链接数据库 取出地区列表
        try:
            alist = Area.objects.all()
        except Exception as e:
            return JsonResponse({'errmsg': '数据出错',
                             'errno': 4001})
        list = []
        # 返回所有的地区名字
        for area in alist:
            list.append({
                'aid':area.id,
                'aname':area.name
            })
        return JsonResponse({'errmsg': '获取成功',
                             'errno': 0,
                             'data': list})


class UserName(LoginRequiredMixin,View):
    '''用户实名认证,先登录'''

    def get(self, request):
        # 查询展示
        real_name = request.user.real_name
        id_card = request.user.id_card
        data = {'real_name':real_name,'id_card':id_card}
        return JsonResponse({'errno': '0',
                             'errmsg': 'ok',
                             'data':data})

    def post(self,request):
        # 取出json数据
        dict = json.loads(request.body)
        real_name = dict.get('real_name')
        id_card = dict.get('id_card')
        # 存入数据库
        if not all([real_name,id_card]):
            return JsonResponse({'errmsg': '缺少必传参数',
                                 'errno': '4103'})

        if not re.match(r'^\d{17}[\d|x]$', id_card):
            return JsonResponse({'errno': '4103',
                                 'errmsg': '身份证格式有误'})

        if not re.match(r'^[\u4e00 -\u9fa5]{2,10}$', real_name):
            return JsonResponse({'errno': '4103',
                                 'errmsg': '姓名格式有误'})

        try:
            User.objects.filter(id=request.user.id).update(real_name=real_name,
                                                           id_card=id_card)
        except Exception as e:
            return JsonResponse({'errmsg': '数据出错',
                                 'errno': '4004'})

        return JsonResponse({'errno': '0',
                             'errmsg': '认证信息保存成功',
                             'real_name': real_name,
                             'id_card': id_card})


class HomeList(LoginRequiredMixin,View):
    '''我的房屋列表'''

    def get(self, request):
        houses = []
        # 链接数据库 取出对象查询集
        try:
            list = House.objects.filter(user_id=request.user.id)
        except Exception as e:
            return JsonResponse({'errmsg': '数据库查询出错',
                                 'errno': '4001'})
        # 返回房屋信息


        fdfs = FastDFSStorage()  # 创一个fdfs的对象

        for h in list:
            houses.append({
                "address": h.address,
                "area_name": h.area.name,
                "ctime": h.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                "house_id": h.id,
                "img_url": fdfs.url(str(h.index_image_url)),
                "order_count": h.order_count,
                "price": h.price,
                "room_count": h.room_count,
                "title": h.title,
                "user_avatar": fdfs.url(str(h.user.avatar))
            })
        data = {'houses': houses}
        return JsonResponse({'errno': '0',
                             'errmsg': 'ok',
                             'data': data})
